<?php
// +----------------------------------------------------------------------
// | TwoThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.twothink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 楹﹀綋鑻楀効 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace app\home\controller;
use app\home\model\Document;
use think\Cache;
class Index extends Home{
    public function __construct(){
        parent::__construct();
    }
    public function _initialize(){
        //parent::_initialize();
    }

    public static $orderIds = [
        
    ];
    public static $orders = [
        
    ];
    public function InitOrders(){
        $orderList = \think\Db::name('33hao_order_tmp')->field(['order_id','store_id'])->where(['month'=>$this->month])->select();
        shuffle($orderList);
        foreach ($orderList as $order){
            self::$orderIds[] = $order['order_id'];
            $key = $order['order_id'];
            self::$orders[$key] = ['store_id'=>$order['store_id'],'amount'=>0,'goods_num'=>0/* 订单产品个数 */,'goods_count'=>0,/* 订单产品总数量  */'goods_commonid'=>[]/* 平台货号记录 不能超过3个 */,'goods_ids'=>[]];
        }
        return true;
    }
    
    public function InitGoods(){
        $goodList = \think\Db::name('33hao_goods_tmp')->field(['month','goods_id','goods_price','store_id','order_num'])->where(['month'=>$this->month,'order_num'=>['>',0]])->select();
        $list = [];
        foreach ($goodList as $good){
            if($good['order_num'] > 1){
                $num = $good['order_num'];
                $good['order_num'] = 1;//分配一个
                for ($i = 1;$i <= $num;$i++){
                    $list[] = $good;
                }
            }else{
                $list[] = $good;
            }
        }
        shuffle($list);
        return $list;
        
        
        
        $name = 'goods_' .$this->month;
        if(!Cache::has($name)){
            $goodList = \think\Db::name('33hao_goods_tmp')->field(['month','goods_id','goods_price','store_id','order_num'])->where(['month'=>$this->month,'order_num'=>['>',0]])->select();
            $list = [];
            foreach ($goodList as $good){
                if($good['order_num'] > 1){
                    $num = $good['order_num'];
                    $good['order_num'] = 1;//分配一个
                    for ($i = 1;$i <= $num;$i++){
                        $list[] = $good;
                    }
                }else{
                    $list[] = $good;
                }
            }
            shuffle($list);
            Cache($name,$list);
        }
        return Cache::get($name);
    }
    
    public function getOrder($order_id){
        $key = 'orders__' .$order_id;
        return Cache($key);
    }
    
    public function setOrderProduct($order_id,$order,$productIndex,$product){//一次只分配一个产品
        $order = self::$orders[$order_id];
        
        $order['amount'] += $product['goods_price'];
        !in_array($product['goods_ids'], $order['goods_ids']) && $order['goods_num'] += 1;//产品个数
        $order['goods_count'] += 1; 
        !in_array($product['goods_commonid'], $order['goods_commonid']) && $order['goods_commonid'][] = $product['goods_commonid'];
        !in_array($product['goods_ids'], $order['goods_ids']) && $order['goods_ids'][] = $product['goods_ids'];
        
        $month = $this->month;
        $goods_id = $product['goods_id'];
        $price = $product['goods_price'];
        $gc_id = $product['gc_id'];
        \think\Db::query("insert into 33hao_order_goods_tmp (order_id,goods_id,goods_price,goods_num,gc_id,month) values ('{$order_id}','{$goods_id}','{$price}','1','{$gc_id}','{$month}') ON DUPLICATE KEY UPDATE goods_num = goods_num + 1");
        
        self::$orders[$order_id] = $order;
        //Cache($key,$order);
        return true;
    }
    
    public $month ='201807'    ;
	//每个月只一次
    public function index(){
        set_time_limit(0);
        $month = $this->month;
        $products = $this->InitGoods();
        $orders = $this->InitOrders();
//         var_dump(count($products),count(self::$orderIds));die;
        //先保证每个订单有不少于30元的产品
        shuffle(self::$orderIds);
        foreach (self::$orderIds as $order_id){
            $order = self::$orders[$order_id];
            foreach ($products as $productIndex => $product){//分配产品
                if($product['goods_price'] < 30){
                    continue;
                }
                if($product['store_id'] != $order['store_id']){
                    continue;
                }
                $this->setOrderProduct($order_id, $order, $productIndex, $product);
                //消耗了 分配了就下一下产品
                unset($products[$productIndex]);
                break;
            }
        }
        
        //然后继续
        foreach ($products as $productIndex => $product){//分配产品
            shuffle(self::$orderIds);
            foreach (self::$orderIds as $order_id){
                $order = self::$orders[$order_id];
                if($product['store_id'] != $order['store_id']){
                    continue;
                }
                if($order['amount'] == 0){//直接第一次分配
                    $this->setOrderProduct($order_id, $order, $productIndex, $product);
                    //消耗了 分配了就下一下产品
                    unset($products[$productIndex]);
                    break;
                }
                
                if($order['amount'] > 2000 && $product['goods_price'] > 1000){//订单已2000 并下个产品金额大于 1000
                    continue;
                }
                if($order['amount'] > 4000){//订单总金额小于4000
                    continue;
                }
                $rand = rand(1,6);
                if($order['goods_num'] >= $rand){/* 产品个数 */
                    continue;
                }
                $rand2 = rand($order['goods_num'],10);
                if(($order['goods_num']=1 &&  $order['goods_count'] > 5) || ($order['goods_num'] >1 && $order['goods_count'] > $rand2) ){/* 产品总个数 */
                    continue;
                }
                if(count($order['goods_commonid']) > 3){//平台货号不能超过3
                    continue;
                }
                $this->setOrderProduct($order_id, $order, $productIndex, $product);
                unset($products[$productIndex]);
                //消耗了 分配了就下一下产品
                break;
            }
        }
        
        //剩下的随机份了
        foreach ($products as $productIndex => $product){//分配产品
            shuffle(self::$orderIds);
            foreach (self::$orderIds as $order_id){
                $order = self::$orders[$order_id];
                if($product['store_id'] != $order['store_id']){
                    continue;
                }
                $rand = rand(3,6);
                if($order['goods_num'] >= $rand){/* 产品个数 */
                    continue;
                }
                $rand2 = rand($order['goods_num'],10);
                if(($order['goods_num']=1 &&  $order['goods_count'] > 5) || ($order['goods_num'] >1 && $order['goods_count'] > $rand2) ){/* 产品总个数 */
                    continue;
                }
                $this->setOrderProduct($order_id, $order, $productIndex, $product);
                unset($products[$productIndex]);
                //消耗了 分配了就下一下产品
                break;
            }
        }
        die('done');
        
        foreach ($orders as $order){
            foreach ($data[$order['store_id']] as $product){
                if(!isset($productsUsed[$product['goods_id']])){
                    $productsUsed[$product['goods_id']] = 0;
                }
                
                if($productsUsed[$product['goods_id']] > $product['order_num']){//鐢ㄥ浜�
                    //unset($data[$order['store_id']][$product['goods_id']]);//鍒犻櫎浜у搧
                    continue;//涓嬩竴涓骇鍝�
                }
                if(rand(1,3) > 1){
                    continue;
                }
                break;
            }
            try {
                
            $num = 1;//鍏堟瘡涓垎涓�涓�
            \think\Db::name('33hao_order_goods_tmp')->insert([
                'order_id' => $order['order_id'],
                'goods_id' => $product['goods_id'],
                'goods_price' => $product['goods_price'],
                'goods_num' => $num,
                'gc_id'     => $product['gc_id'],
                'month'  => $month
            ]);
            
            $productsUsed[$product['goods_id']] += $num;
            
            $data[$order['store_id']][$product['goods_id']]['order_num'] -= $num;
            if($data[$order['store_id']][$product['goods_id']]['order_num'] < 1){
                unset($data[$order['store_id']][$product['goods_id']]);//鍒犻櫎浜у搧
            }
            } catch (\Exception $e) {
            }
            
        }
        //鏇存柊鍓╀綑鏁伴噺
        \think\Db::query("update 33hao_goods_tmp set leftt=0 where month='{$month}'");//缃浂
        foreach ($data as $store_id => $list){
            foreach ($list as  $goods_id => $product){
                \think\Db::query("update 33hao_goods_tmp set leftt='".$data[$store_id][$goods_id]['order_num']."' where month='{$month}' and goods_id='$goods_id' and store_id='$store_id'");
            }
        }
        echo '1 step done'; 
    }
    
    
    public function check(){
        
        
        
        
        
        
        
        
        
        die('un use');
        
        
        set_time_limit(0);
        $month = $this->month;
        $data = [];
        $products = \think\Db::name('33hao_goods_tmp')->where(['month'=>$month,'leftt'=>['>',0]])->select();
        if(empty($products)){
            echo '2 step done ,not order_num leftt';die;
        }
//         var_dump($products);die;
        foreach ($products as $product){
            if(!$data[$product['store_id']]){
                $data[$product['store_id']] = [];
            }
            $data[$product['store_id']][$product['goods_id']] = $product;
        }
        unset($products);
        $ordersData = [];
        $orders = \think\Db::query("select * from 33hao_order_tmp where month='{$month}' order by rand();");
        $ordersGoods = \think\Db::query("select order_id,count(1) as 'count',sum(goods_num*goods_price) as 'total' from 33hao_order_goods_tmp where month='{$month}' group by order_id");
        $allTotoal = 0;
        foreach ($ordersGoods as $detail){
            if(!isset($ordersData[$detail['order_id']])){
                $ordersData[$detail['order_id']]['count'] = $detail['count'];
                $ordersData[$detail['order_id']]['total'] = $detail['total'];
                $ordersData[$detail['order_id']]['total_0'] = $detail['total'];
            }
            $allTotoal += $detail['total'];
        }
        unset($ordersGoods);
//         var_dump($ordersData);die;
        foreach ($data as $store_id => $list){
            if($allTotoal > 6700000){break;die('2 step done ,閿�鍞瓒冲浜�');}
            foreach ($list as $goods_id => $product){
                foreach ($orders as $order){
                    if(!isset($ordersData[$order['order_id']])){
                        $ordersData[$order['order_id']]['count'] = 1;//棣栨閮芥槸娣诲姞涓�涓殑
                        $ordersData[$order['order_id']]['total'] =50;//棣栨閮芥槸娣诲姞涓�涓殑
                        $ordersData[$order['order_id']]['total_0'] =50;//棣栨閮芥槸娣诲姞涓�涓殑
                    }
                    $count = $ordersData[$order['order_id']]['count'];
                    $total = $ordersData[$order['order_id']]['total'];
                    $total_0 = $ordersData[$order['order_id']]['total_0'];
                    $rand = rand(2,4);
                    $price = $product['goods_price'];
//                     var_dump($count,$rand,$price);die;
                    if(( $count > 6) || $count > 8 || $total_0 > 200 || $count > $rand || ($count > 1 && $price > 500) || $total > 5000){
                        continue;
                    }
                    //
                    if($data[$store_id][$goods_id]['leftt']  < 1){
                        unset($data[$store_id][$goods_id]);//鍒犻櫎浜у搧
                        break;
                    }
                    $num = $product['leftt'] > 10 ? rand(1,2) : 1;
                    \think\Db::query("insert into 33hao_order_goods_tmp (order_id,goods_id,goods_price,goods_num,gc_id,month) values ('" .$order['order_id']. "','{$goods_id}','{$price}','{$num}','". $product['gc_id'] ."','{$month}') ON DUPLICATE KEY UPDATE goods_num = goods_num + {$num}");
                    $data[$store_id][$goods_id]['leftt'] -= $num;
                    $ordersData[$order['order_id']]['count'] +=1;//娣诲姞涓�涓竴鏉¤褰�
                    $ordersData[$order['order_id']]['total'] +=$price * $num;//娣诲姞涓�涓竴鏉¤褰�
                    $allTotoal += $price * $num;//娣诲姞涓�涓竴鏉¤褰�
                    
                }
            }
        }
        //姣忔鍙墽琛屽畬閲嶆柊鏇存柊 浜у搧鍓╀綑鏁扮洰
        
        //鏇存柊鍓╀綑鏁伴噺
        \think\Db::query("update 33hao_goods_tmp set leftt=0 where month='{$month}'");//缃浂
        foreach ($data as $store_id => $list){
            foreach ($list as  $goods_id => $product){
                \think\Db::query("update 33hao_goods_tmp set leftt='".$data[$store_id][$goods_id]['leftt']."' where month='{$month}' and goods_id='$goods_id' and store_id='$store_id'");
            }
        }
        echo '2 step done';
    }

}
